import { defineComponent, ref, onMounted, onUpdated } from "vue";
import './index.scss';
import axios from 'axios';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import { ElCard } from 'element-plus';
import 'element-plus/theme-chalk/dark/css-vars.css'
import { nextTick } from "process";
const Home = defineComponent({
    setup() {
        const messages = ref([]); // 存储聊天记录
        const lastSpokenText = ref(''); // 记录上次朗读的文本
        const off = ref(false);
        const messageContainerRef = ref<HTMLElement | null>(null); // 用于存储消息容器的引用

        let requestQueue = [];  // 用于存储实时请求的队列
        let isProcessing = false;  // 用于跟踪是否正在处理请求
        const drawer = ref(false)
        const activeName = ref('first')
        const wsOff = ref(false)
        const voice = ref('')
        const textarea = ref('')
        const voiceSave = ref('')
        const textareaSave = ref('')

        const voiceTypes = [
            {
              name: "清区大叔",
              scene: "趣味方言",
              language: "中文",
              voice_type: "zh_female_wanqudashu_moon_bigtts"
            },
            {
              name: "呆萌川妹",
              scene: "趣味方言",
              language: "中文",
              voice_type: "zh_female_daimengchuanmei_moon_bigtts"
            },
            {
              name: "广州德哥",
              scene: "趣味方言",
              language: "中文",
              voice_type: "zh_male_guozhoudege_moon_bigtts"
            },
            {
              name: "北京小爷",
              scene: "趣味方言",
              language: "中文",
              voice_type: "zh_male_beijingxiaoye_moon_bigtts"
            },
            {
              name: "少年柠檬/Brayan",
              scene: "通用场景",
              language: "多语种",
              voice_type: "zh_male_shaonianzixin_moon_bigtts"
            },
            {
              name: "魅力女友",
              scene: "角色扮演",
              language: "中文",
              voice_type: "zh_female_meilinvyou_moon_bigtts"
            },
            {
              name: "深夜播客",
              scene: "角色扮演",
              language: "中文",
              voice_type: "zh_male_shenyeboke_moon_bigtts"
            },
            {
              name: "撒娇萝妹",
              scene: "趣味方言",
              language: "中文",
              voice_type: "zh_female_yuanqinvyou_moon_bigtts"
            },
            {
              name: "浩宇小哥",
              scene: "趣味方言",
              language: "中文",
              voice_type: "zh_male_haoyuxiaoge_moon_bigtts"
            }
          ];
          
        // 直接设置 MarkdownIt 配置
        const md = new MarkdownIt({
            breaks: true, // 自动换行
            highlight: function (str, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    try {
                        return '<pre class="hljs"><code>' +
                            hljs.highlight(str, { language: lang }).value +
                            '</code></pre>';
                    } catch (__) { }
                }
                return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
            }
        });

        // 异步处理队列中的请求
            const processQueue = async () => {
                if (isProcessing || requestQueue.length === 0) {
                    return;  // 如果已经在处理或队列为空，直接返回
                }

                isProcessing = true;  // 设置正在处理标志

                while (requestQueue.length > 0) {
                    const text = requestQueue.shift();  // 从队列中取出第一个请求
                    try {
                        const audioUrl = await synthesizeSpeech(text);  // 发送请求并等待结果
                        await playAudio(audioUrl);  // 播放音频并等待结束
                    } catch (error) {
                        console.error('处理音频合成或播放时出错:', error);
                    }
                }

                isProcessing = false;  // 处理完成，重置标志
            };


            // 添加请求到队列中并触发处理
            const addToQueue = (text) => {
                requestQueue.push(text);
                processQueue();  // 每次添加新请求时，尝试处理队列
            };


            const synthesizeSpeech = async (text) => {
                if (!text) {
                    return;
                }
            
                try {
                    const response = await axios.post('http://localhost:3201/api/synthesize', { text, voice: voiceSave.value }, {
                        responseType: 'arraybuffer' // 确保返回的是二进制数据
                    });
            
                    // 假设 response 是你的 axios 请求返回的对象
                    const arrayBuffer = response.data;
            
                    // 将 ArrayBuffer 转换为 Blob
                    const blob = new Blob([arrayBuffer], { type: 'audio/wav' });
            
                    // 创建一个可以使用的音频 URL
                    const audioUrl = URL.createObjectURL(blob);
            
                    return audioUrl;
                } catch (error) {
                    console.log(`请求失败: ${error}`);
                    throw error;  // 抛出错误，让调用方处理
                }
            };

            const playAudio = async (audioUrl) => {
                return new Promise((resolve, reject) => {
                    const audio = new Audio(audioUrl);
                    audio.play().then(() => {
                        console.log('Audio is playing');
                    }).catch((error) => {
                        console.error('Failed to play audio:', error);
                        reject(error);
                    });
            
                    audio.onended = () => {
                        console.log('Audio finished playing');
                        resolve();  // 音频播放结束后，resolve promise
                    };
                });
            };
        onMounted(() => {
            const local = localStorage.getItem('messages');
            const savedMessages = local ? JSON.parse(local) : [];
            messages.value = savedMessages;
            const set1 = localStorage.getItem('voiceSave')
            const set2 = localStorage.getItem('textareaSave')
            voiceSave.value = set1 || "zh_male_beijingxiaoye_moon_bigtts"
            voice.value = set1 || "zh_male_beijingxiaoye_moon_bigtts"
            textareaSave.value = set2 || "你是智宝AI，你现在是直播间的AI人工智能，请回答弹幕的问题,并引导用户关注私信了解"
            textarea.value = set2 || "你是智宝AI，你现在是直播间的AI人工智能，请回答弹幕的问题,并引导用户关注私信了解"
        });

        onUpdated(() => {
            scrollToBottom(); // 每次更新后滚动到底部
        });

        const dataFilter = (data) => {
            data.forEach((val) => {
                const existingMessage = messages.value.find(
                    (element) => element.name === val.name && element.msg === val.msg
                );
                if (!existingMessage) {
                    messages.value.push({ ...val, answer: '' });
                }
            });

            if (messages.value.length > 0) {
                handleMessage(messages.value);
            }
        };

        const handleMessage = (data) => {
            if (off.value) return;
            data.some((element, ind) => {
                if(element.msg == '分享了直播') return
                if (!element.answer) {
                    getOpenAIResponse('我叫：' + element.name + ',我想问:' + element.msg)
                        .then((response) => {
                            messages.value[ind].answer = response;
                            localStorage.setItem('messages', JSON.stringify(messages.value));
                            off.value = false;
                            setTimeout(() => {
                                scrollToBottom();
                            }, 500)
                            // speakText(convertMarkdownToText(response));
                            addToQueue(convertMarkdownToText(response))
                        })
                        .catch((error) => {
                            off.value = false;
                            console.error('Error in handleMessage:', error);
                        });
                    return true; // 跳出循环
                }
                return false; // 继续处理
            });
        };

        const convertMarkdownToText = (markdown) => {
            return markdown
                .replace(/\*\*(.*?)\*\*/g, '$1')
                .replace(/\*(.*?)\*/g, '$1')
                .replace(/`(.*?)`/g, '$1')
                .replace(/\n\n/g, '\n')
                .replace(/\n/g, ' ');
        };

        const speakText = (text) => {
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.rate = 1.5; // 语速
            utterance.lang = 'zh-CN'; // 设置语言为中文

            utterance.onend = () => {
                off.value = false;
            };

            utterance.onstart = () => {
                console.log('开始朗读');
            };

            window.speechSynthesis.speak(utterance);
        };

        const getOpenAIResponse = (message) => {
            off.value = true;
            return new Promise((resolve) => {
                axios.post('http://localhost:3201/api/get-ai-response', { userMessage: message , system: textareaSave.value })
                    .then(response => {
                        resolve(response.data.response);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            });
        };

        const scrollToBottom = () => {
            const container = messageContainerRef.value;
            if (container) {
                container.scrollTop = container.scrollHeight;
            }
        };

        const action = () => {
            drawer.value = true
        }

        const getAction = () => {
            voiceSave.value = voice.value
            textareaSave.value = textarea.value
            localStorage.setItem('voiceSave', voiceSave.value)
            localStorage.setItem('textareaSave', textareaSave.value)
            activeName.value = "second"
            nextTick(() => {
                scrollToBottom();
            })
            if(wsOff.value) return
            const ws = new WebSocket('ws://localhost:3201');
            wsOff.value = true
            ws.onopen = () => {
                console.log('Connected to WebSocket server');
            };

            ws.onmessage = (event) => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(event.data, 'text/html');

                const messageElements = doc.querySelectorAll('.ReactVirtualized__Grid__innerScrollContainer > div');
                const newMessages = [];

                messageElements.forEach((element) => {
                    const name = element.querySelector('.chatItemNickName--AetDL')?.textContent?.trim();
                    const msg = element.querySelector('.chatItemDesc--KHShO')?.textContent?.trim();
                    if (name && msg) {
                        if(msg != '分享了直播') {
                            newMessages.push({ name, msg });
                        }                 
                    }
                });
                console.log(newMessages)
                dataFilter(newMessages);
            };

            ws.onclose = () => {
                console.log('Disconnected from WebSocket server');
                wsOff.value = false
            };

            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
                wsOff.value = false
            };
        };
        
        const handleClick = (tab) => {
            if (tab.props.name === 'second') {
                // 切换到 "Config" 标签页时，滚动到底部
                scrollToBottom();
              }
          }

        return () => (
            <div class='home dark' >
                <el-tabs type="border-card" vModel={activeName.value} class="demo-tabs" onTabClick={(e) => handleClick(e)}>
                    <el-tab-pane label="直播配置" name="first">
                      <p>请选择音色</p>
                      <el-select vModel={voice.value} placeholder="Select" >
                        {
                            voiceTypes.map(item => {
                                return <el-option
                                    key={item.voice_type}
                                    label={item.name}
                                    value={item.voice_type}
                                >
                                    <span style="float: left">{ item.name }</span>
                                    <span
                                        style="
                                        float: right;
                                        color: var(--el-text-color-secondary);
                                        font-size: 13px;
                                        "
                                    >
                                        { item.language } { item.scene }
                                    </span>
                                    </el-option>
                            })
                        }
                        </el-select>
                        <p>您的自定义主体内容</p>
                        <el-input
                            vModel={textarea.value}
                            type="textarea"
                            placeholder="Please input"
                        />
                        <el-button type="primary" round onClick={() => {getAction()}}>保存设置，并开始直播</el-button>
                    </el-tab-pane>
                    <el-tab-pane label="内容输出" name="second">
                        <div id="messages" ref={messageContainerRef} style="height: 100%; overflow-y: auto;">
                            {messages.value.map((msg, index) => (
                                <div className="card" key={index}>
                                    <ElCard style="max-width: 480px">
                                        {{
                                            header: () => (
                                                <div class="card-header">
                                                    <span>{msg.name} ：  {msg.msg}</span>
                                                    {/* <br />
                                                    <br />
                                                    <span>{msg.msg}</span> */}
                                                </div>
                                            ),
                                            default: () => (
                                                <p class="text item" v-html={msg.answer ? md.render(msg.answer) : '思考中...'}></p>
                                            ),
                                        }}
                                    </ElCard>
                                </div>
                            ))}
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="数字人" name="three">
                       <p style="color:#fff">正在开发中...</p>
                    </el-tab-pane>
    
                </el-tabs>
               
            </div>
        );
    },
});

export default Home;
